from django.shortcuts import HttpResponse
from sklearn.externals import joblib
from common import util
import fuse_frame

# Create your views here.


def index(request):
    # request.POST
    # request.GET
    return HttpResponse("HelloWorld")


def result(request):
    # request.POST
    # request.GET
    get_latitude = request.GET.get('latitude')
    get_longitude = request.GET.get('longitude')
    get_speed = request.GET.get('speed')
    get_time = int(float(request.GET.get('time')))
    # 加载dbscan模型
    dbsc = joblib.load('../period/cache/dbscan.pkl')
    get_location = dbsc.fit_predict([[get_latitude, get_longitude]])
    # 处理速度传感器数据
    if get_speed == '\\N':
        get_speed = 0  # Static ： 0
    elif float(get_speed) <= 0.5:
        get_speed = 0  # Static ： 0
    elif float(get_speed) <= 1.0:
        get_speed = 1  # Walking ： 1
    elif float(get_speed) <= 2:
        get_speed = 2  # Running ： 2
    else:
        get_speed = 3  # Use Transaction ： 3

    feature_dict = {'location': get_location, 'speed': get_speed, 'time': get_time}
    relative_header = r'..'
    app_list = fuse_frame.result_app(5449.0, feature_dict, relative_header)
    return HttpResponse(str(app_list))


def rec_result(request):
    # request.POST
    # request.GET
    get_latitude = request.GET.get('latitude')
    get_longitude = request.GET.get('longitude')
    get_speed = request.GET.get('speed')
    get_time = int(float(request.GET.get('time')))
    # 加载dbscan模型
    dbsc = joblib.load('../period/cache/dbscan.pkl')
    get_location = dbsc.fit_predict([[get_latitude, get_longitude]])
    # 处理速度传感器数据
    if get_speed == '\\N':
        get_speed = 0  # Static ： 0
    elif float(get_speed) <= 0.5:
        get_speed = 0  # Static ： 0
    elif float(get_speed) <= 1.0:
        get_speed = 1  # Walking ： 1
    elif float(get_speed) <= 2:
        get_speed = 2  # Running ： 2
    else:
        get_speed = 3  # Use Transaction ： 3

    feature_dict = {'location': get_location, 'speed': get_speed, 'time': get_time}
    relative_header = r'..'
    app_list = fuse_frame.result_app(5449.0, feature_dict, relative_header)
    # app_list = ['com.android.browser', 'com.netease.cloudmusic', 'com.oschina.app', 'com.sdu.didi.psnger', 'com.tencent.mm']
    return HttpResponse(str(app_list))

# 持久化存储数据
def pub_user_data(request):
    info_str = request.POST.get('info')
    if info_str:
        if util.save_app_data(info_str):
            return HttpResponse('用户信息存储成功')
    else:
        return HttpResponse('接收到的用户信息为空')
